// pages/danger/selfAdd/index.js
import Dialog from '../../../dist/dialog/dialog.js';
import Toast from '../../../dist/toast/toast.js';
var app = getApp()
var util = require('../../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseUrl: app.globalData.baseUrl,


    inspectId: 0,
    inspectList: [],
    title: '检查表标题',
    head: ['序号', '检查项目', '检查内容', '操作'],
    hiddenModal: true,
    inspectPublicId: 0,
    processInstanceId: "",
    taskId: "",
    dangerLevelOptions: ['一般(C级)', '一般(B级)', '重大(A级)'],


    selectLevel: "一般（C级）",
    inspectListPublic: {},
    inspectListPublicIndex: 0, //当前编辑的检查项目在inspectList中的index
    deadline: "",
    inspectResult: "", //检查记录
    needChange: false,
    tempImagePaths: [],
    inspectImageIds: [],
    dangerTypeOptions:['安全管理类','从业人员类','作业场所类','设备设施类'],
    selectType:'安全管理类',
    applyUserName:'',
    applyUserId:'',
    changeRequire:'',

    selectPersonDialog:true,
    searchName:'',
    nameArray:[],
    userIds:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    this.setData({
      inspectId: options.inspectId,
      taskId: options.taskId,
      title: options.inspectName
    })
    var inspect = options.inspect
    that.loadInspectPublicDetail(options.inspectId);
  },
  /**
     * 加载发布的隐患排查的检查单
     */
  loadInspectPublicDetail(inspectPublicId) {

    var that = this
    var header;
    that.setData({
      inspectPublicId: inspectPublicId
    })
    header = {
      'Cookie': wx.getStorageSync("sessionid") //读取cookie
    };
    wx.request({
      url: app.globalData.baseUrl + '/safe/danger/inspectListPublic/find',
      header: header,
      method: "POST",
      data: {
        inspectPublicId: inspectPublicId,
        needChange: '1'
      },
      success(res) {
        var inspectList = res.data.data
        for (var i = 0; i < inspectList.length; i++) {
          if (inspectList[i].deadline) {
            inspectList[i].deadlineStr = util.formatTime(new Date(inspectList[i].deadline))
          } else {
            inspectList[i].deadlineStr = "无"
          }
          if (!inspectList[i].hiddenDangerLevel) {
            inspectList[i].hiddenDangerLevel = "无"
          }
        }
        that.setData({
          inspectList: res.data.data
        })
      }
    })
  },

  /**
   * 显示记录的窗口
   */
  showInspectModal(e) {
    var index = e.currentTarget.dataset.index
    var inspectPublicListId = e.currentTarget.dataset.inpsectpubliclistid
    var inspectPublicList = this.data.inspectList[index]
    this.setData({
      hiddenModal: false,
    })
    this.setData({
      inspectListPublic: inspectPublicList,
      inspectListPublicIndex: index
    })
    this.initInspectListPublic(inspectPublicList)
  },
  /**
  * 点击记录，加载隐患记录的信息
  */
  initInspectListPublic(inspectPublicList) {
    var deadline = ''
    if (inspectPublicList.deadline) {
      deadline = util.formatTime(new Date(inspectPublicList.deadline), 'Y/M/D')
    } else {
      deadline = util.formatTime(new Date())
    }
      let tempPicList=[];
      inspectPublicList.dangerPics.forEach(function (item) {
          tempPicList.push({
              fId:item.fId,
              url:app.globalData.fileUrl+item.path+'?x-oss-process=image/resize,m_fixed,h_70,w_70',
              oriUrl:app.globalData.fileUrl+item.path
          })
      });
    this.setData({
      inspectResult: inspectPublicList.inspectResult,
      tempImagePaths: tempPicList,
      applyUserName: inspectPublicList.applyUserName,
      applyUserId: inspectPublicList.applyUserId,
      deadline: deadline,
      selectLevel: inspectPublicList.hiddenDangerLevel,
      selectType: inspectPublicList.dangerType ? inspectPublicList.dangerType : '安全管理类',
      changeRequire: inspectPublicList.changeRequire
    })
  },
  /**
   * 隐藏窗口
   */
  hiddenInspectModal() {
    this.setData({
      hiddenModal: true
    })
  },
  /**
   * 保存单个隐患检查记录
   */
  saveInspectList() {
    var that = this
    var header = {
      'Cookie': wx.getStorageSync("sessionid") //读取cookie
    };
    var params = {
      deadline: this.data.deadline,
      id: this.data.inspectListPublic.id,
      applyUserId: this.data.applyUserId,
      applyUserName: this.data.applyUserName,
      hiddenDangerLevel: this.data.selectLevel,
      dangerType: this.data.selectType,
      changeRequire: this.data.inspectResult
    }
    wx.request({
      url: app.globalData.baseUrl + '/safe/danger/inspectListPublic/update',
      header: header,
      method: "POST",
      data: params,
      success(res) {
        if (res.data.success) {
          var param = "inspectList[" + that.data.inspectListPublicIndex + "]"
          var inspectListPublic = that.data.inspectList[that.data.inspectListPublicIndex]
          inspectListPublic.deadline = that.data.deadline
          inspectListPublic.hiddenDangerLevel = that.data.selectLevel
          inspectListPublic.inspectResult = that.data.inspectResult
          inspectListPublic.deadlineStr = util.formatTime(new Date(that.data.deadline))
          inspectListPublic.applyUserName = that.data.applyUserName
          inspectListPublic.applyUserId = that.data.applyUserId
          inspectListPublic.dangerType = that.data.selectType
          inspectListPublic.changeRequire = that.data.changeRequire
          var inspectList = that.data.inspectList
          inspectList[that.data.inspectListPublicIndex] = inspectListPublic
          that.setData({
            inspectList: inspectList,
            hiddenModal: true
          })

        }
      }
    })

  },

  /**
   * 隐患级别选择
   */
  dangerLevelSelect(e) {
    this.setData({
      selectLevel: this.data.dangerLevelOptions[e.detail.value]
    })
    var param = "inspectPublicList.hiddenDangerLevel"
    this.setData({
      [param]: this.data.dangerLevelOptions[e.detail.value]
    })
  },
  /**
   * 隐患类型选择
   */
  dangerTypeSelect(e){
    this.setData({
      selectType: this.data.dangerTypeOptions[e.detail.value]
    })
    var param = "inspectListPublic.dangerType"
    this.setData({
      [param]: this.data.dangerTypeOptions[e.detail.value]
    })
  },
   /**
   * 整改要求记录
   */
  bindChangeRequireBlur(e){
    this.setData({
      changeRequire: e.detail.value
    })
  },
  /**
   * 记录隐患整改期限
   */
  inspectListChangeData(e) {
    var param = "inspectListPublic.deadline"
    this.setData({
      [param]: e.detail.value
    })
    this.setData({
      deadline: e.detail.value
    })
  },
  /**
   * 预览隐患照片
   */
  previewDangerImage(e) {
      var src = e.currentTarget.dataset.src;
      var imageList = new Array();
      for (var i = 0; i < this.data.tempImagePaths.length; i++) {
          imageList.push(this.data.tempImagePaths[i].oriUrl)
      }
      wx.previewImage({
          current: src,
          urls: imageList,
      })
  },
  /**
   * 打开人员选择弹出框
   */
  openSelectPersonDialog(){
    this.setData({
      selectPersonDialog: false,
      hiddenModal: true
    })
  },
  /**
   * 关闭人员选择弹出框
   */
  hiddenPersonDialog(){
    this.setData({
      selectPersonDialog: true,
      hiddenModal: false
    })
  },
  /**
   * 搜索人员响应
   */
  searchNameClick(val){
    this.setData({
      searchName: val.detail
    })
    this.searchName();
  },
   /**
   * 记录搜索人员
   */
  onSearchNameChange(val){
    this.setData({
      searchName: val.detail
    })
  },
  /**
   * 搜索人民
   */
  searchName() {
    var that = this;
    var header;
    header = {
      'Cookie': wx.getStorageSync("sessionid") //读取cookie
    };
    wx.request({
      header: header,
      url: app.globalData.baseUrl + '/safe/user/find',
      method: 'get',
      data: { username: this.data.searchName, pageSize:5},
      success(res) {
        var tempList = [];
        for (var i = 0; i < res.data.data.list.length; i++) {
          tempList.push({ userId: res.data.data.list[i].userId, userName: res.data.data.list[i].username });
        }
        that.setData({
          nameArray: tempList
        })
      }
    })
  },
  /**
   * 点击选择人员
   */
  nameClick(item){
    this.setData({
      applyUserName: item.target.dataset.username,
      applyUserId: item.target.dataset.userid,
      selectPersonDialog: true,
      hiddenModal: false
    })
  },
  /**
   * 判断所有隐患是否都有负责人
   */
  judgeApplyUser(){
    let tempArr=[];
    for (var i = 0;i<this.data.inspectList.length;i++){
      if (this.data.inspectList[i].applyUserId){
        tempArr.push(this.data.inspectList[i].applyUserId);
      }else{
        return i;
      }
    }
    this.setData({
      userIds: Array.from(new Set(tempArr))
    })
    return -1;
  },
  /**
   * 生成整改单
   */
  saveInspectDate() {
    var applyUserIndex = this.judgeApplyUser()
    if (applyUserIndex<0){
      var header;
      header = {
        'Cookie': wx.getStorageSync("sessionid") ,//读取cookie
        'content-type': 'application/x-www-form-urlencoded'
      };
      var that = this
      var params = {
        id: that.data.inspectPublicId,
        taskId: this.data.taskId,
        check: false,
        evaluate: false,
        userIds: this.data.userIds
      }
      wx.request({
        header: header,
        url: app.globalData.baseUrl + '/safe/dangerFlow/doTask',
        method: 'POST',
        data: params,
        success(res) {
          wx.showToast({
            title: '提交成功',
            icon: 'none',
          })
          setTimeout(function () {
            wx.navigateBack({
              delta: 1
            })},1000);
        }
      })
    }else{
      wx.showToast({
        title: '第' + (applyUserIndex+1) + '条隐患未填写负责人',
        icon: 'none',
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})